package com.dingding.special.user.validate.service.impl;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.base.dto.AbstractValiResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.Phonevalidate;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.paravalidate.ValiResult;
import com.dingding.common.core.util.paravalidate.ValidateUtil;
import com.dingding.facade.queue.dto.msg.MessageRequestsDTO;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.special.model.message.MessageModel;
import com.dingding.special.user.validate.dao.IValidateCodeDao;
import com.dingding.special.user.validate.dto.ReqGetValidateCodeDTO;
import com.dingding.special.user.validate.message.ValidateMessage;
import com.dingding.special.user.validate.service.IValidateCodeService;

/**
 * 
 * @ClassName: IValidateNumService 
 * @Description:手机验证码验证
 * @author CHEHAUNBO 
 * @date 2016年8月21日 下午4:56:16
 * @since V2.4.0
 * 
 */
@Component("validateCodeService")
public class ValidateCodeServiceImpl extends AbstractValiResponse implements IValidateCodeService {

	private static Logger log = Logger.getLogger(ValidateCodeServiceImpl.class);

	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;

	@Resource(name = "validateCodeDao")
	private IValidateCodeDao validateCodeDao;

	@Resource(name = "queueFacade_cus")
	private IQueueFacade queueFacade;

	/**
	 * 手机验证码校验
	 * 
	 * @Title: telPhoneCodeValidate 
	 * @param telPhone 手机号
	 * @param validaCode 验证码
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public boolean telPhoneCodeValidate(String telPhone, String validaCode) {

		Criterion criterion = Restrictions.and(Restrictions.eq("phoneNum", telPhone), Restrictions.eq("isValid", 1));

		Phonevalidate phonevalidate = null;
		try {

			phonevalidate = criteriaBaseDao.queryCriteriaListUnique(Phonevalidate.class, criterion);

			if (phonevalidate != null) {
				if (validaCode.equals(phonevalidate.getValidateNum())) {
					phonevalidate.setIsValid(2); // 验证码设为无效
					return true;
				} else {

					if (phonevalidate.getValidateCodeNumber() == null) {
						phonevalidate.setValidateCodeNumber(0);
					}
					phonevalidate.setValidateCodeNumber(phonevalidate.getValidateCodeNumber() + 1);
					return false;
				}
			}

		} catch (Exception e) {
			log.error("验证手机验证码出现异常！", e);
		}

		return false;

	}

	/**
	 * 
	 * 发送手机验证码
	 * 
	 * 注意此方法只负责添加内容到队列中，具体发送任务由队列完成
	 * 
	 * @Title: sendPhoneNum 
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	public boolean sendPhoneNum(String telPhone) {

		String validateCode = ToolUtil.generateCellPhoneValNum();

		try {

			if (validateCodeDao.saveVliateCode(telPhone, validateCode)) { // 保存验证码到数据成功

				String messageContent = MessageModel.GetValidateCodeModel(validateCode);
				MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
				messageRequestsDTO.setTelPhone(telPhone);
				messageRequestsDTO.setMessageContent(messageContent);
				// 添加短信内容到队列中
				boolean isSuccess = queueFacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));

				if (!isSuccess) {
					throw new Exception("发送手机验证码添加短信消息到队列中出现异常！");
				}

				return true;
			}

		} catch (Exception e) {
			log.error("发送手机验证码出现异常！", e);
		}

		return false;
	}

	/**
	 * 
	 * 发送手机验证码
	 * 
	 * 注意此方法只负责添加内容到队列中，具体发送任务由队列完成
	 * 
	 * @Title: sendPhoneNum 
	 * @return ResponseEntity<Object>
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	public ResponseEntity<Object> sendPhoneNum_(ReqGetValidateCodeDTO reqGetValidateCodeDTO) {

		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqGetValidateCodeDTO,
				ReqGetValidateCodeDTO.class);

		// 参数不合法，存在空值
		if (!valiResult.isAvailable()) {
			return super.error(valiResult);
		}

		if (this.sendPhoneNum(reqGetValidateCodeDTO.getPhoneNum())) {
			return success(HttpStatus.SC_OK);
		}

		return super.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, ValidateMessage.VALIDATE_SEND_FAIL,
				ValidateMessage.VALIDATE_SEND_FAIL);
	}

}
